<?php

namespace app\http\middleware;

use think\DB;
use think\facade\Request;

class CheckIp
{
    public function handle($request, \Closure $next)
    {
        // if (!session('?checkIp')) {
        //     dump();
        //     return json([
        //         'code' => '4000',
        //         'msg' => lang('4000'),
        //     ]);
        // }
        $ip_row = DB::name('check_ip')->where("ip", Request::ip())->find();
        if ($ip_row) {
            if ($ip_row['count'] > 9) { //$ip_row['time'] + 60 - time() > 0 &&
                return json([
                    'code' => '1',
                    'msg' => "访问过于频繁,ip被禁止",
                ]);
            }

            if ($ip_row['time'] + 3 - time() > 0 && $ip_row['count'] > 9) { //$ip_row['time'] + 60 - time() > 0 &&
                return json([
                    'code' => '1',
                    'msg' => "访问过于频繁,ip被禁止",
                ]);
            }

            if ($ip_row['time'] + 3 - time() < 0) {
                DB::name('check_ip')->where("ip", Request::ip())->update([
                    "time" => time(),
                    "count" => 1,
                    "userid" => session('?memberInfo') ? session('memberInfo.userid') : 0,
                ]);
            } else {
                DB::name('check_ip')->where("ip", Request::ip())->setInc("count");
            }
        } else {
            DB::name('check_ip')->where("ip", Request::ip())->insert([
                "ip" => Request::ip(),
                "time" => time(),
                "count" => 1,
                "userid" => session('?memberInfo') ? session('memberInfo.userid') : 0,
            ]);
        }
        $checkIp = session('checkIp');
        
        if ($checkIp) {
            if ($checkIp['time'] + 30 - time() > 0) {
                $checkIp['count']++;
            } else {
                $checkIp = [
                    "count" => 1,
                    "time" => time(),
                ];
            }
            if ($checkIp['count'] > 100) {
                return json([
                    'code' => '1',
                    'msg' => "访问过于频繁",
                ]);
            }
            session('checkIp', $checkIp);
        } else {
            session('checkIp', [
                "count" => 1,
                "time" => time(),
            ]);
        }
        return $next($request);
    }
}
